package com.xc.hotelmgr.webapi.modules.op.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.xc.hotelmgr.webapi.common.annotation.SysLog;
import com.xc.hotelmgr.webapi.common.utils.HttpClient;
import com.xc.hotelmgr.webapi.modules.dt.entity.DtEntity;
import com.xc.hotelmgr.webapi.modules.dt.entity.StoreEntity;
import com.xc.hotelmgr.webapi.modules.dt.entity.StorePfEntity;
import com.xc.hotelmgr.webapi.modules.dt.service.DtService;
import com.xc.hotelmgr.webapi.modules.dt.service.StorePfService;
import com.xc.hotelmgr.webapi.modules.dt.service.impl.StoreServiceImpl;
import com.xc.hotelmgr.webapi.modules.ht.entity.HtBrandEntity;
import com.xc.hotelmgr.webapi.modules.ht.entity.HtCityinfoEntity;
import com.xc.hotelmgr.webapi.modules.ht.service.HtBrandService;
import com.xc.hotelmgr.webapi.modules.ht.service.HtCityinfoService;
import com.xc.hotelmgr.webapi.modules.mq.dto.SendAllList;
import com.xc.hotelmgr.webapi.modules.mq.dto.UpDownList;
import com.xc.hotelmgr.webapi.modules.mq.service.HotelToMQService;
import com.xc.hotelmgr.webapi.modules.op.entity.*;
import com.xc.hotelmgr.webapi.modules.op.service.GroupService;
import com.xc.hotelmgr.webapi.modules.op.service.MtFeignService;
import com.xc.hotelmgr.webapi.modules.op.service.TaskStatusService;
import com.xc.hotelmgr.webapi.modules.sys.controller.AbstractController;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.xc.hotelmgr.webapi.modules.op.service.DtUpHtlService;
import com.xc.hotelmgr.webapi.common.utils.PageUtils;
import com.xc.hotelmgr.webapi.common.utils.R;



/**
 * 
 *
 * @author kemmy
 * @email kemmy@gmail.com
 * @date 2020-09-30 08:51:24
 */
@EnableAsync
@RestController
@RequestMapping("op/dtuphtl")
public class DtUpHtlController extends AbstractController {
    @Autowired
    private DtService dtService;

    @Autowired
    private HtCityinfoService htCityinfoService;

    @Autowired
    private StorePfService storePfService;

    @Autowired
    private StoreServiceImpl storeService;

    @Autowired
    private HtBrandService htBrandService;

    @Autowired
    private GroupService groupService;

    @Autowired
    private DtUpHtlService dtUpHtlService;

    @Autowired
    private HotelToMQService hotelToMQService;

    /**
     * 查询机构列表
     */
    @SysLog
    @RequestMapping("/dtpf")
    @RequiresPermissions("op:dtuphtl:list")
    public R listDtPf(@RequestParam Map<String, Object> params){
        String dtId = getUserDtId().toString();
        String inSql = "SELECT id FROM dt_dt WHERE FIND_IN_SET(id, getChild("+ dtId+ "))";
        List<DtEntity> dts =  dtService.getBaseMapper().selectList(new QueryWrapper<DtEntity>().inSql("id",inSql));
        List<StorePfEntity> spfs = storePfService.getBaseMapper().selectList(new QueryWrapper<StorePfEntity>());
        return R.ok().put("dts", dts).put("spfs",spfs);
    }

    /**
     * 查询城市信息下拉列表
     */
    @SysLog
    @RequestMapping("/citys")
    @RequiresPermissions("op:dtuphtl:list")
    public R data(@RequestParam Map<String, Object> params){
        List<HtCityinfoEntity> list = htCityinfoService.queryData(params);
        return R.ok().put("list", list);
    }

    /**
     * 查询销售平台列表
     */
    @SysLog
    @RequestMapping("/pf")
    @RequiresPermissions("op:dtuphtl:list")
    public R listPf(){
        List<StorePfEntity> list = storePfService.getBaseMapper().selectList(new QueryWrapper<StorePfEntity>());
        return R.ok().put("list", list);
    }
    /**
     * 查询店铺列表
     */
    @SysLog
    @RequestMapping("/store")
    @RequiresPermissions("op:dtuphtl:list")
    public R listStore(@RequestParam Map<String, Object> params){
        List<StoreEntity> list = storeService.sqlSelectByDtPf(params);
        return R.ok().put("list", list);
    }

    /**
     * 查询品牌列表
     */
    @SysLog
    @RequestMapping("/brand")
    @RequiresPermissions("op:dtuphtl:list")
    public R listBrand(@RequestParam Map<String, Object> params){
        List<HtBrandEntity> list = htBrandService.getBaseMapper().selectList(new QueryWrapper<HtBrandEntity>());
        return R.ok().put("list", list);
    }

    /**
     * 查询分组
     */
    @SysLog
    @RequestMapping("/group")
    @RequiresPermissions("op:dtuphtl:list")
    public R listGroup(@RequestParam Map<String, Object> params){
        String ownerDeptStr = getUserOwnerDept();
        String[] ownerDept = null;
        String dtId = (String) params.get("dtId");
        // 如果选择了机构，查询指定机构的数据
        if (!StringUtils.isEmpty(dtId) && !StringUtils.equals(dtId, getUserDtId().toString())) {
            ownerDept = new String[1];
            ownerDept[0] = dtId;
        } else {
            ownerDept = ownerDeptStr.split("\\,");
        }
        params.put("ownerDept", ownerDept);
        List<GroupEntity> list = groupService.sqlQuery(params);
        return R.ok().put("list", list);
    }
    /**
     * 列表
     */
    @SysLog
    @RequestMapping("/htls")
    @RequiresPermissions("op:dtuphtl:list")
    public R listHotel(@RequestParam Map<String, Object> params){
        PageUtils page = dtUpHtlService.sqlQueryHtlPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @SysLog
    @RequestMapping("/list")
    @RequiresPermissions("op:dtuphtl:list")
    public R list(@RequestParam Map<String, Object> params){
        String ownerDeptStr = getUserOwnerDept();
        String[] ownerDept = null;
        String dtId = (String) params.get("dtId");
        // 如果选择了机构，查询指定机构的数据
        if(!StringUtils.equals(dtId,getUserDtId().toString())){
            ownerDept = new String[1];
            ownerDept[0] = dtId;
        }else {
            ownerDept = ownerDeptStr.split("\\,");
        }
        params.put("ownerDept",ownerDept);
        PageUtils page = dtUpHtlService.sqlQueryPage(params);
        System.out.println(page.getList());
        return R.ok().put("page", page);
    }
    /**
     * 保存
     */
    @SysLog
    @RequestMapping("/save")
    @RequiresPermissions("op:dtuphtl:save")
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public R save(@RequestBody UpHtlDto upHtlDto){
        R r = dtUpHtlService.prePareSave(upHtlDto);
        if((int)r.get("code") == 0) {
            List<DtUpHtlEntity> upHtlEntities = (List<DtUpHtlEntity>) r.get("upHtl");
            dtUpHtlService.saveUphtl(upHtlEntities);
        }
        r.remove("upHtl");
        return  r;

    }

    /**
     * 删除
     */
    @SysLog
    @RequestMapping("/delete")
    @RequiresPermissions("op:dtuphtl:delete")
    public R delete(@RequestBody Long[] ids){
		dtUpHtlService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }


    /**
     * 推送店铺下指定酒店（meit 从store表里获取dtid）
     * @param sendAllList
     * @return
     */
    @SysLog
    @RequestMapping("/ali/send")
    @RequiresPermissions("op:hotel:send")
    public R send(@RequestBody SendAllList sendAllList) {
        try{
            hotelToMQService.sendAllList(sendAllList);
            return  R.ok("成功推送了" + sendAllList.getHotelList().size() + "个酒店;");
        }catch (Exception ex){
            return  R.error("推送失败了" + ex.toString());
        }
    }

    /**
     * 删除飞猪店铺上的指定酒店(meit 从store表里取了dtId）
     * @param hotelUpDownHtlDto
     * @return
     */
    @SysLog
    @RequestMapping("/ali/del")
    @RequiresPermissions("op:hotel:up")
    public R aliDel(@RequestBody HotelUpDownHtlDto hotelUpDownHtlDto){
        int unUsableCount = 0;
        int usableCount = 0;
        List<Long> hotelList = Lists.newArrayList();
        for(HotelDto HotelDto : hotelUpDownHtlDto.getHotelList() ){
            // 如果没有推送，则不允许上下架
            if(HotelDto.getStatus() != -1){
                usableCount ++;
                hotelList.add(HotelDto.getHotelId());
            }else {
                unUsableCount++;
            }
        }
        UpDownList upDownList = new UpDownList();
        upDownList.setStoreId(hotelUpDownHtlDto.getStoreId());
        upDownList.setStatus(hotelUpDownHtlDto.getStatus());
        upDownList.setHotelList(hotelList);
        try{
            hotelToMQService.upDownList(upDownList);
            return   R.ok("成功删除了" + usableCount + "个酒店;" + unUsableCount + "个酒店未删除。");
        }catch (Exception ex){
            return  R.error("删除失败了，" + ex.toString());
        }
    }


    /**
     * 上架
     */
    @SysLog
    @RequestMapping("/ali/up")
    @RequiresPermissions("op:hotel:up")
    public R up(@RequestBody HotelUpDownHtlDto hotelUpDownHtlDto){
       return upDown(hotelUpDownHtlDto);
    }

    /**
     * 下架
     */
    @SysLog
    @RequestMapping("/ali/down")
    @RequiresPermissions("op:hotel:down")
    public R down(@RequestBody HotelUpDownHtlDto hotelUpDownHtlDto){
        return upDown(hotelUpDownHtlDto);
    }


    /**
     * 上下架酒店
     */
    private R upDown(HotelUpDownHtlDto hotelUpDownHtlDto){
        int unUsableCount = 0;
        int usableCount = 0;
        List<Long> hotelList = Lists.newArrayList();
        for(HotelDto HotelDto : hotelUpDownHtlDto.getHotelList() ){
            // 如果没有推送，则不允许上下架
            if(HotelDto.getStatus() != -1){
                usableCount ++;
                hotelList.add(HotelDto.getHotelId());
            }else {
                unUsableCount++;
            }
        }
        UpDownList upDownList = new UpDownList();
        upDownList.setStoreId(hotelUpDownHtlDto.getStoreId());
        upDownList.setStatus(hotelUpDownHtlDto.getStatus());
        upDownList.setHotelList(hotelList);
        try{
            hotelToMQService.upDownList(upDownList);
            if(upDownList.getStatus() == 0) {
                return  R.ok("成功上架或删除了" + usableCount + "个酒店;" + unUsableCount + "个酒店未推送。");
            }else {
                return R.ok("成功下架或删除了" + usableCount + "个酒店;" + unUsableCount + "个酒店未推送。");
            }
        }catch (Exception ex){
            return R.error("上下架失败，"+ ex.toString());
        }
    }

    @SysLog
    @RequestMapping("/redis/init")
    @RequiresPermissions("op:init:hotel")
    public R redisInit(@RequestParam Map<String, Object> params){
        dtUpHtlService.redisInit();
        return R.ok();
    }
    @SysLog
    @RequestMapping("/auto/order/{id}/{isAuto}")
    @RequiresPermissions("op:hotel:up")
    public R autoOrder(@PathVariable("id")  Long id,@PathVariable("isAuto")  Integer isAuto){
        DtUpHtlEntity dtUpHtlEntity = new DtUpHtlEntity();
        dtUpHtlEntity.setId(id);
        dtUpHtlEntity.setIsAuto(isAuto);
        dtUpHtlService.updateById(dtUpHtlEntity);
        return R.ok("设置成功");
    }
}
